<?php

namespace Brandon
{
	/**
	 * This class demonstrates using getter/setter methods instead of a fluid interface
	 */
	class LineItem
	{
		/**
		 * Line item name
		 * @var string
		 */
		protected $_name;

		/**
		 * Line item md5 key
		 * @var string
		 */
		protected $_md5Name;

		/**
		 * Line item price
		 * @var decimal
		 */
		protected $_price;

		/**
		 * Line item quantity
		 * @var int
		 */
		protected $_quantity = 0;

		/**
		 * Generate a random price between 1 and 9999.99
		 * @return decimal
		 */
		protected function _generatePrice()
		{
			$dollars = rand(1, 9999);
			$cents = str_pad(rand(0, 99), 2, '0', STR_PAD_LEFT);
			$value = $dollars . '.' . $cents;

			return filter_var($value, FILTER_VALIDATE_FLOAT, array('options' => array('decimal' => '.')));
		}

		/**
		 * Get line item price using its name value
		 * @param string $value
		 * @return decimal
		 */
		public function generatePrice($value)
		{
			// Assign name and md5 hash name for line item
			$this->_name = $value;
			$this->_md5Name = md5($value);

			// Check session for previously generated price
			if (isset($_SESSION[$this->_md5Name]))
			{
				$this->_price = $_SESSION[$this->_md5Name];
				return $this->_price;
			}

			// Price is not in cache, generate a price
			$this->_price = $this->_generatePrice();

			// Save price to cache
			$_SESSION[$this->_md5Name] = $this->_price;

			return $this->_price;
		}

		/**
		 * Get the line item price
		 * @return int
		 */
		public function getPrice()
		{
			return $this->_price;
		}

		/**
		 * Set the line item quantity
		 * @param int
		 * @return Brandon\LineItem
		 */
		public function setQuantity($value)
		{
			$this->_quantity = (int) $value;
			return $this;
		}

		/**
		 * Get the line item quantity
		 * @return int
		 */
		public function getQuantity()
		{
			return (int) $this->_quantity;
		}

		/**
		 * Return quantity x price
		 * @return decimal
		 */
		public function getTotal()
		{
			$value = $this->_quantity * $this->_price;
			return number_format($value, 2, '.', '');
		}
	}
}
